package com.icangya.service.impl;

import com.icangya.DAO.IQRcodeOfCSDAO;
import com.icangya.domain.CSQRcode;
import com.icangya.service.ICSQRManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.UUID;

@Service("CSQRManageServiceImpl")
public class CSQRManageServiceImpl implements ICSQRManageService{

    @Autowired
    private IQRcodeOfCSDAO iqRcodeOfCSDAO;

    @Override
    public String getCSQR() {
        CSQRcode qrcs=iqRcodeOfCSDAO.getCSQR();
        if(qrcs==null){
            return "";
        }
        return qrcs.getPath();
    }

    @Override
    public Serializable setCSQR(HttpServletRequest request) {
        String path;

        try {
            path=(String) request.getSession().getAttribute("csqr");
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        //如果session中csqr不为空值，则保存到数据库
        if(path==null||path.equals("")){return 0;}
        CSQRcode csqr=new CSQRcode(path);
        Serializable r=iqRcodeOfCSDAO.setCSQR(csqr);
        if(!r.equals(0)){request.getSession().setAttribute("csqr","");}
        return r;
    }

    @Override
    public void uploadCSQR(MultipartFile file, HttpServletRequest request) {

        //上传的目录地址
        String uploadDir= request.getSession().getServletContext().getRealPath("/")+"upload/shop/csqr/";
        //如果目录不存在，自动创建文件夹
        File dir=new File(uploadDir);
        if(!dir.exists()){
            dir.mkdir();
        }

        String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //上传文件名
        String filename= UUID.randomUUID()+suffix;

        //服务器端保存的文件对象
        File serverFile=new File(uploadDir+filename);
        //将上传的文件写入到服务器端文件内
        try {
            file.transferTo(serverFile);
            request.getSession().setAttribute("csqr","upload/shop/csqr/"+filename);
        } catch (IOException e) {
            e.printStackTrace();
            request.getSession().setAttribute("csqr","");
        }

    }
}
